package com.study.util.crypt;

import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import sun.misc.BASE64Decoder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 读取OpenSSL生成的RSA key
 * Created by meen on 2017/12/8.
 */
public class KeyReadUtil {


    public static String pemReadPub(String path) {
        try {
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String readLine;
            String a = "";
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                if (readLine.charAt(0) != '-') {
                    sb.append(readLine + "\r");
                    a += readLine;
                }
            }
            System.err.println(path + " :" + a);
            byte[] buffer = new BASE64Decoder().decodeBuffer(a);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            System.err.println("公钥:" + EncryptUtil.BASE64Encode(publicKey.getEncoded()));
            return EncryptUtil.BASE64Encode(publicKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }

    public static String pemReadPri(String path) {
        try {
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String readLine;
            String a = "";
            PrivateKey privateKey = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                if (readLine.charAt(0) != '-') {
                    sb.append(readLine + "\r");
                    a += readLine;
                }
            }
            System.err.println(path + " :" + a);
            byte[] buffer = new BASE64Decoder().decodeBuffer(a);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            try { // try to decode with PKCS8
                PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
                privateKey = keyFactory.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                try { // try to decode with PKCS1
                    RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) ASN1Sequence.fromByteArray(buffer));
                    RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
                    privateKey = keyFactory.generatePrivate(rsaPrivKeySpec);
                } catch (InvalidKeySpecException e2) {
                    throw new Exception("Invalid key spec, only support PKCS1/PKCS8");
                }
            }
            System.err.println("私钥:" + EncryptUtil.BASE64Encode(privateKey.getEncoded()));
            return EncryptUtil.BASE64Encode(privateKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }

}
